<?php
class Advmenusystem_AdminMenusController extends Core_Controller_Action_Admin {

  protected $_menus;
  protected $_enabledModuleNames;

  public function init() {
    // Get list of menus
    $menusTable = Engine_Api::_()->getDbtable('menus', 'core');
    $menusSelect = $menusTable->select();
    $this->view->menus = $this->_menus = $menusTable->fetchAll($menusSelect);

    $this->_enabledModuleNames = Engine_Api::_()->getDbtable('modules', 'core')->getEnabledModuleNames();
	$this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
      ->getNavigation('advmenusystem_admin_main', array(), 'advmenusystem_admin_main_menus');
  }

  public function indexAction() {
    $this->view->name = $name = $this->_getParam('name', 'core_main');

    // Get list of menus
    $menus = $this->_menus;
    
    // Check if selected menu is in list
    $selectedMenu = $menus->getRowMatching('name', $name);
    if (null === $selectedMenu) {
      throw new Core_Model_Exception('Invalid menu name');
    }
    $this->view->selectedMenu = $selectedMenu;

    // Make select options
    $menuList = array();
    foreach ($menus as $menu) {
    	if($menu->name == "core_main" || $menu->name == "advmenusystem_mini")
      		$menuList[$menu->name] = $this->view->translate($menu->title);
    }
    $this->view->menuList = $menuList;

    // Get menu items
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuItemsSelect = $menuItemsTable->select()
                    ->where('menu = ?', $name)
                    ->order('order');
    if (!empty($this->_enabledModuleNames)) {
      $menuItemsSelect->where('module IN(?)', $this->_enabledModuleNames);
    }
    $this->view->menuItems = $menuItems = $menuItemsTable->fetchAll($menuItemsSelect);
  }

  public function createAction() {

    $this->view->name = $name = $this->_getParam('name');

    // Get list of menus
    $menus = $this->_menus;

    // Check if selected menu is in list
    $selectedMenu = $menus->getRowMatching('name', $name);

    if (null === $selectedMenu) {
      throw new Core_Model_Exception('Invalid menu name');
    }
    $this->view->selectedMenu = $selectedMenu;

    // Get form
    $this->view->form = $form = new Advmenusystem_Form_Admin_Menu_ItemCreate();

    //if ($name != "advnotification_mini") {
      //$form->removeElement('submenu');
    //}
    if(Engine_Api::_()->getApi('settings', 'core')->getSetting('avdmenusystem.submenu', 1) == 0)
    {
        $form->removeElement('submenu');
    }
    else if($name != "advmenusystem_mini" && $name != "core_main")
    {
          $form->removeElement('submenu');
    }
    if($name  == "advmenusystem_mini")
		$form->removeElement('target');
    // Check stuff
    if (!$this->getRequest()->isPost()) {
      return;
    }
    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    // Save
    $values = $form->getValues();
    $label = $values['label'];
    unset($values['label']);
    $submenu = '';
    $flag_unique = '0';
    if(Engine_Api::_()->getApi('settings', 'core')->getSetting('avdmenusystem.submenu', 1) == 1 && ($name == "advmenusystem_mini" || $name == "core_main"))
    { 
      $submenu = $values['submenu'];
      unset($values['submenu']);
      $flag_unique = '1';
    }
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');

    $menuItem = $menuItemsTable->createRow();
    $menuItem->label = $label;
    $menuItem->params = $values;
    $menuItem->menu = $name;
    $menuItem->module = 'core'; // Need to do this to prevent it from being hidden
    $menuItem->plugin = '';
    $menuItem->submenu = $submenu;
    $menuItem->flag_unique = $flag_unique;
    $menuItem->custom = 1;
    $menuItem->save();

    $menuItem->name = 'custom_' . sprintf('%d', $menuItem->id);
    $menuItem->save();

    $this->view->status = true;
    $this->view->form = null;
    return $this->_forward('success', 'utility', 'core', array(
        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Menu Added.')),
        'layout' => 'default-simple',
        'parentRefresh' => true,
    ));
  }

  public function editAction() {
    $this->view->name = $name = $this->_getParam('name');
    $this->view->flag_unique = $flag_unique = $this->_getParam('flag_unique');

    // Get menu item
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuItemsSelect = $menuItemsTable->select()
                    ->where('name = ?', $name)
                    ->where('flag_unique = ?', $flag_unique);
    if (!empty($this->_enabledModuleNames)) {
      $menuItemsSelect->where('module IN(?)', $this->_enabledModuleNames);
    }
    $this->view->menuItem = $menuItem = $menuItemsTable->fetchRow($menuItemsSelect);

    if (!$menuItem) {
      throw new Core_Model_Exception('missing menu item');
    }

    // Get form
    $this->view->form = $form = new Advmenusystem_Form_Admin_Menu_ItemEdit();

    // Make safe
    $menuItemData = $menuItem->toArray();
    if (isset($menuItemData['params']) && is_array($menuItemData['params']))
      $menuItemData = array_merge($menuItemData, $menuItemData['params']);
    if (!$menuItem->custom) {
      $form->removeElement('uri');
    }
	if($menuItem->menu  == "advmenusystem_mini")
		$form->removeElement('target');
    if(Engine_Api::_()->getApi('settings', 'core')->getSetting('avdmenusystem.submenu', 1) == 1
        && ($menuItem->menu  == "advmenusystem_mini" || $menuItem->menu  == "core_main"))
    {
          $old_sub = $menuItem->submenu;
          if ($old_sub == 1) {
            $form->submenu->setValue('1');
          }
          else
            $form->submenu->setValue('');
    }
    else
    {
          $form->removeElement('submenu');  
    }

    if (!$this->getRequest()->isPost()) {
      $form->populate($menuItemData);
      return;
    }
    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    // Save
    $values = $form->getValues();
    $menuItem->label = $values['label'];
    if(Engine_Api::_()->getApi('settings', 'core')->getSetting('avdmenusystem.submenu', 1) == 1
       && ($menuItem->menu  == "advmenusystem_mini" || $menuItem->menu  == "core_main"))
    {
      $menuItem->submenu = $values['submenu'];
    }
    unset($values['label']);
    if ($menuItem->custom) {
      $menuItem->params = $values;
    } else if (!empty($values['target'])) {
      $menuItem->params = array_merge($menuItem->params, array('target' => $values['target']));
    }
    if (isset($values['enabled'])) {
      $menuItem->enabled = (bool) $values['enabled'];
    }
    $menuItem->save();

    $this->view->status = true;
    $this->view->form = null;
    
	return $this->_forward('success', 'utility', 'core', array(
		'messages' => array(Zend_Registry::get('Zend_Translate')->_('Menu Edited.')),
		'layout' => 'default-simple',
		'parentRefresh' => true,
	));
    
  }

  public function deleteAction() {
    $this->view->name = $name = $this->_getParam('name');
    $this->view->flag_unique = $flag_unique = $this->_getParam('flag_unique');

    // Get menu item
    $menuItemsTable = Engine_Api::_()->getDbtable('menuItems', 'core');
    $menuItemsSelect = $menuItemsTable->select()
                    ->where('name = ?', $name)
                    ->where('flag_unique = ?', $flag_unique)
                    ->order('order ASC');
    if (!empty($this->_enabledModuleNames)) {
      $menuItemsSelect->where('module IN(?)', $this->_enabledModuleNames);
    }
    $this->view->menuItem = $menuItem = $menuItemsTable->fetchRow($menuItemsSelect);

    if (!$menuItem || !$menuItem->custom) {
      throw new Core_Model_Exception('missing menu item');
    }

    // Get form
    $this->view->form = $form = new Core_Form_Admin_Menu_ItemDelete();

    // Check stuff
    if (!$this->getRequest()->isPost()) {
      return;
    }
    if (!$form->isValid($this->getRequest()->getPost())) {
      return;
    }

    $menuItem->delete();

    $this->view->form = null;
    $this->view->status = true;
  }

  public function orderAction() {
    if (!$this->getRequest()->isPost()) {
      return;
    }

    $table = $this->_helper->api()->getDbtable('menuItems', 'core');
    $menuitems = $table->fetchAll($table->select()->where('menu = ?', $this->getRequest()->getParam('menu')));
    foreach ($menuitems as $menuitem) {
      $menuitem->order = $this->getRequest()->getParam('admin_menus_item_' . $menuitem->name);
      $menuitem->save();
    }
    return;
  }

}
